<?php
declare(strict_types=1);

namespace app\common\lib;

use Pheanstalk\Contract\ResponseInterface;
use Pheanstalk\Pheanstalk;

/**
 * | Notes：消息队列工具
 * +----------------------------------------------------------------------
 * | PHP Version 7.2+
 * +----------------------------------------------------------------------
 * | Copyright (c) 2011-2020 https://www.xxq.com.cn, All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 和好 <389123492@qq.com>
 * +----------------------------------------------------------------------
 * | Date: 2020/4/19 19:03
 * +----------------------------------------------------------------------
 */
trait Queue
{
    private static $instance;

    /**
     * 获取对象信息
     *
     * @param string $tube
     *
     * @return bool|object|\Pheanstalk\Job
     */
    public static function getStatsJob(string $tube = 'default')
    {
        $pheanstalk = self::getInstance();
        $job        = $pheanstalk->watch($tube)->reserve();

        return $job;
    }

    /**
     * 单例
     *
     * @return Pheanstalk
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new Pheanstalk('127.0.0.1', 11300);
        }

        return self::$instance;
    }

    /**
     * 获取管道信息
     *
     * @return array
     */
    public static function getListTubes()
    {
        $pheanstalk = self::getInstance();
        $job        = $pheanstalk->listTubes();

        return $job;
    }

    /**
     * 获取队列状态
     *
     * @param string $tube
     *
     * @return ResponseInterface
     */
    public static function getStatsTube(string $tube = 'default')
    {
        $pheanstalk = self::getInstance();
        return $pheanstalk->statsTube($tube);
    }

    /**
     * 删除队列
     *
     * @param string $tube
     */
    public static function deleteQueue(string $tube = 'default')
    {
        $pheanstalk = self::getInstance();
        $job        = $pheanstalk
            ->watch($tube)
            ->reserve(10);

        return $pheanstalk->delete($job);
    }

    /**
     * 设置队列
     * @param array  $data
     * @param string $tube
     *
     * @return mixed
     */
    public static function setQueue(array $data, string $tube = 'default')
    {
        $pheanstalk = self::getInstance();
        //第三步：发送信息
        return $pheanstalk->putInTube($tube, json_encode($data), Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY, Pheanstalk::DEFAULT_TTR);
    }
}
